package com.purchasing.system.controller;

import com.purchasing.system.model.Permission;
import com.purchasing.system.model.Role;
import com.purchasing.system.repository.PermissionRepository;
import com.purchasing.system.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.Set;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/roles/{roleId}/permissions")
public class RolePermissionController {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    // 获取角色所有权限
    @GetMapping
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<Set<Permission>> getRolePermissions(@PathVariable Long roleId) {
        Optional<Role> role = roleRepository.findById(roleId);
        return role.map(value -> new ResponseEntity<>(value.getPermissions(), HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    // 为角色添加权限
    @PostMapping("/{permissionId}")
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<?> addPermissionToRole(
            @PathVariable Long roleId,
            @PathVariable Long permissionId) {

        Optional<Role> roleOpt = roleRepository.findById(roleId);
        Optional<Permission> permissionOpt = permissionRepository.findById(permissionId);

        if (roleOpt.isEmpty() || permissionOpt.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        Role role = roleOpt.get();
        Permission permission = permissionOpt.get();

        if (role.getPermissions().contains(permission)) {
            return new ResponseEntity<>("Permission already assigned to role", HttpStatus.CONFLICT);
        }

        role.getPermissions().add(permission);
        roleRepository.save(role);

        return new ResponseEntity<>(HttpStatus.OK);
    }

    // 批量更新角色权限
    @PutMapping
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<?> updateRolePermissions(
            @PathVariable Long roleId,
            @RequestBody List<Long> permissionIds) {

        Optional<Role> roleOpt = roleRepository.findById(roleId);
        if (roleOpt.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        Role role = roleOpt.get();

        // 直接使用 List<Long> 参数查询
        Set<Permission> permissions = permissionRepository.findAllByIdIn(permissionIds);

        // 验证查询到的权限数量是否与请求一致
        if (permissions.size() != permissionIds.size()) {
            return ResponseEntity.badRequest()
                    .body("部分权限ID不存在");
        }

        role.setPermissions(permissions);
        roleRepository.save(role);

        return ResponseEntity.ok().build();
    }
    // 从角色移除权限
    @DeleteMapping("/{permissionId}")
//    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public ResponseEntity<?> removePermissionFromRole(
            @PathVariable Long roleId,
            @PathVariable Long permissionId) {

        Optional<Role> roleOpt = roleRepository.findById(roleId);
        if (roleOpt.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        Role role = roleOpt.get();
        boolean removed = role.getPermissions().removeIf(p -> p.getId().equals(permissionId));

        if (removed) {
            roleRepository.save(role);
            return new ResponseEntity<>(HttpStatus.OK);
        } else {
            return new ResponseEntity<>("Permission not assigned to role", HttpStatus.NOT_FOUND);
        }
    }
}